package week6;

public class HashSearching {
    int m;  // m是除数
    int count = 0;
    HashNode[] list ; // 地址存放
    int times = 0;
    int conflictTimes = 0;

    public HashSearching(int m)
    {
        this.m = m;
        list = new HashNode[m];
    }

    public int Remainder(int num)
    {
        int a;
        a = num % m;
        return a;
    }

    public void addInAddress(int[] ele)
    {
//        for (int x = 0;x < ele.length;x++)
//        {
//            int remainder = Remainder(ele[x]);
//        }
        int x = 0;
        int temp;

        while (x < ele.length)
        {
            temp = Remainder(ele[x]);
            HashNode node = new HashNode(ele[x]);
            if (list[temp] == null)
            {
                list[temp] = node;
            }
            else
            {
                conflictTimes++;
                HashNode current = list[temp];
                while (current.getNext()!= null)
                {
                    current = current.getNext();
                    conflictTimes++;
                }
                current.setNext(node);
            }
            x++;
            times++;
            count++;
        }

    }

    public boolean search(int[] ele, int num)
    {
        int temp;
        temp = Remainder(num);
        if (list[temp] != null)
        {
            if (list[temp].getEle() == num)
            {

                return true;
            }
            else
            {
                HashNode current = list[temp];
                while (current.getNext() != null && current.getEle() != num)
                {
                    current = current.getNext();
                }
                times++;
                return current.getEle() == num;
            }
        }
        else
        {
            times++;
            return false;
        }
    }

    public void calASL()
    {
        double ASL = 0;
        ASL = (double) (times + conflictTimes)/count;
        System.out.println("冲突次数： " + conflictTimes);
        System.out.println("平均查找长度： " + ASL);
    }
}
